(function() {
	var canvas, ctx, onError, onSuccess, onTrainClose, photosSended, refreshCamera;
	var setupWS, train, sendPhoto, video;

	video = document.querySelector('video');
	canvas = document.querySelector('canvas');
	ctx = canvas.getContext('2d');
	ctx.strokeStyle = '#ff0';
	ctx.lineWidth = 2;
	photosSended = 0;

	$("#msg").hide();

	onError = function(e){
		alert("No se tuvo acceso a la cámara web. Error: " + e);
	};

	onSuccess = function(localMediaStream){
		video.src = webkitURL.createObjectURL(localMediaStream);
		setInterval(refreshCamera, 1);
	};

	refreshCamera = function(){
		ctx.drawImage(video, 0, 0, 320, 240);
	};

	setupWS = function(url, close){
		var _ref;
		if((_ref = window.ws) != null){
			_ref.close();
		}

		window.ws = new WebSocket("ws://" + location.host + "/" + url);
		window.ws.onopen = function(){
			return console.log("Opened websocket " + url);
		};
		window.ws.onmessage = function(event){
			if(event.data == "success"){
				photosSended++;
				alert('Se agregó correctamente la nueva fotografía.');
			}
		};
		return window.ws.onclose = close;
	};

	sendPhoto = function() {
		ctx.drawImage(video, 0, 0, 320, 240);
		return canvas.toBlob(function(blob) {
			var _ref;
			return (_ref = window.ws) != null ? _ref.send(blob) : void 0;
		}, 'image/jpeg');
	};

	onTrainClose = function(){
		if(photosSended > 0){
			$("#msg").text("Espere un momento por favor...");
			$("#msg").show("slow");

			$.post('/train').success(function(){
				alert('Las nuevas fotografías están listas para ser procesadas.');
				window.location.href = "/";
			});
		}else{
			window.location.href = "/";
		}
	};

	$('#uploadPhoto').click(function(event){
		event.preventDefault();
		sendPhoto();
	});

	$('#finishUpload').click(function(event){
		event.preventDefault();
		onTrainClose();
	});

	navigator.webkitGetUserMedia({
		'video': true,
		'audio': false
	}, onSuccess, onError);

	setupWS('extraphoto', onTrainClose);
}).call(this);
